<template lang="html">
  <div class="post-article">
    <el-form ref="form" :model="form" label-width="80px">

      <!-- 标签 -->
      <el-form-item label="标签" v-show="showLabel">
          <el-cascader
          expand-trigger="hover"
          :options="handleOptions"
          v-model="form.tag"
          @change="handleChange">
        </el-cascader>
      </el-form-item>

      <!-- 标题 -->
      <el-form-item :label="title" v-show="hasTitle">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <!-- 浏览量 -->
      <el-form-item label="浏览量" v-show="showReadingAmount">
        <el-input v-model="form.readingAmount"></el-input>
      </el-form-item>
      <!-- 作者 -->
      <el-form-item label="作者" v-show="hasAuthor">
        <el-input v-model="form.author"></el-input>
      </el-form-item>

      <!-- 图片上传 -->
      <el-form-item :label="imageLabel" v-show="isBidsImage">
        <!-- <upload-image @upload="upload" @del="del"></upload-image> -->
        <el-upload
          class="upload-demo"
          multiple
          list-type="picture-card"
          action="https://api.zgwyzxw.cn/files"
          :headers="headers"
          :data="uploadData"
          accept="image/png, image/jpeg, image/gif, image/jpg"
          :on-success="handleSuccess"
          :on-remove="handleFileRemove"
          ref="upload"
          :file-list="imgList"
          >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog v-model="dialogVisible" size="tiny">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
<!-- accept="*.csv,*.doc,*.dot,*.pdf,*.ppt,*.wps" -->
      <el-form-item label="文件上传" v-show="isBidsFile">
        <el-upload
          class="upload-demo"
          action="https://api.zgwyzxw.cn/files"
          :file-list="fileList"
          :headers="headers"
          :uploadData="uploadData"
          :on-success="handleFileSuccess"
          :on-remove="handleFileRemove">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>

      <div class="editor-wrapper">
        <div id="editor"></div>
      </div>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{btnContent}}</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>

import {loadToken} from 'common/js/cache.js'

import {submitArticle, getDetail, updateDeatil} from 'api/article.js'

import {tagOption} from 'common/js/tagOption.js'

import CasCader from 'components/backend/cascader/cascader.vue'

import WangEditor from 'wangEditorjy'

import '../../../../static/js/wangEditor.js'

import UploadImage from 'components/backend/uploadImage/uploadImage'

import {delOneArrItem} from 'common/js/delOneArrItem.js'

import {filterObj} from 'common/js/filterObj.js'

import {setObjName} from 'common/js/setObjName.js'

export default {
  data() {
    return {
      editor: '',
      btnContent: '立即创建',
      currentId: '',
      form: {
        title: '',
        author: '',
        tag: [],
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: '',
        readingAmount: ''
      },
      uploadSuccess: [],
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      uploadData: {
        // 这里需要修改
        prefix: 'article/sfsdf/'
      },
      imgArr: [],
      fileArr: [],
      isBidsImage: false,
      isBidsFile: false,
      hasAuthor: true,
      imgList: [],
      allId: [],
      showReadingAmount: false,
      imageLabel: '图片上传',
      showLabel: true,
      hasTitle: true,
      title: '标题'
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    upload(file) {
      this.uploadSuccess.push(file.data[0].id)
    },
    del(file) {
      let delItemIndexId = file.response.data[0].id
      this.uploadSuccess = delOneArrItem(this.uploadSuccess, delItemIndexId)
    },
    handleChange() {
      let tag = this.form.tag[0]
      // 控制组件的显示与隐藏
      // 表单的上传还有很多上传限制的，例如在上传案例的时候，上传的封面只能是一个
      if (tag === 'callbids') {
        this.isBidsImage = true
        this.isBidsFile = true
        this.hasAuthor = false
      } else if (tag === 'zixun') {
        this.isBidsImage = true
        this.isBidsFile = false
        this.hasAuthor = true
        this.imageLabel = '封面上传'
      } else if (tag === 'case') {
        this.hasAuthor = false
        this.title = '小区'
        this.isBidsImage = true
        this.imageLabel = '封面上传'
      } else {
        this.isBidsImage = false
        this.hasAuthor = true
      }
    },
    onSubmit() {
      if (this.btnContent === '立即创建') {
        this._submitArticle(this.form.title, this.form.author, this.form.tag[1] ? this.form.tag[1] : this.form.tag[0], this.editor.txt.html())
      } else {
        this._updateDetail(this.currentId)
      }
    },
    handleSuccess(file) {
      this.allId.push(file.data[0].id)
    },
    _submitArticle(title, author, tag, content) {
      let fileid = this.allId.join()
      submitArticle(title, author, tag, fileid, content, loadToken()).then((res) => {
        if (res.result === 'OK') {
          this.$message({
            type: 'success',
            message: '文章发表成功'
          })
          this.$router.go(-1)
          this.form.title = ''
          this.form.author = ''
          this.editor.txt.html('')
        }
      })
    },
    _getDetail(id) {
      getDetail(id).then((res) => {
        let item = res
        let newArr = item.tag.split('-')
        newArr[1] = item.tag
        if (item.tag === 'callbids') {
          this.isBidsImage = true
          this.hasAuthor = false
        } else if (item.tag === 'zixun') {
          this.isBidsImage = true
          this.hasAuthor = false
        }
        this.form.tag = newArr
        this.form.title = item.title
        this.form.author = item.author
        this.editor.txt.html(item.content)
        // 设置浏览量
        this.form.readingAmount = item.readingAmount
        // 设置图片列表
        this.imgList = filterObj(res.files)
        // 设置文件列表
        this.fileList = setObjName(filterObj(res.files, 'file'))
        // 获取图片id
        for (let i in this.imgList) {
          this.allId.push(this.imgList[i].id)
        }
        // 获取文件id
        for (let j in this.fileList) {
          this.allId.push(this.fileList[j].id)
        }
        // 上面是可以封装起来的
      })
    },
    _updateDetail(id) {
      let fileid = this.allId.join()
      updateDeatil(id, this.form.title, this.form.author, this.form.readingAmount, this.form.region, fileid, this.editor.txt.html(), loadToken()).then((res) => {
        this.$message({
          type: 'success',
          message: '文章修改成功'
        })
        this.$router.push('/backend/index/article')
      })
    },
    handleFileSuccess(file) {
      this.allId.push(file.data[0].id)
    },
    handleFileRemove(file, fileList) {
      this.delOneFile(file)
    },
    delOneFile(file) {
      for (let i in this.allId) {
        if (file.id === this.allId[i]) {
          this.allId.splice(i, 1)
        }
      }
    }
  },
  created() {
    this.currentId = this.$route.query.id
    if (this.currentId) {
      this.btnContent = '修改'
      this.showReadingAmount = true
      this.showLabel = false
      this._getDetail(this.currentId)
    }
    this.$nextTick(() => {
      this.editor = new WangEditor('#editor')
      this.editor.customConfig.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'foreColor',  // 文字颜色
        'list',  // 列表
        'justify',  // 对齐方式
        'image',  // 插入图片
        'table'  // 表格
      ]
      this.editor.customConfig.menuFixed = true
      this.editor.customConfig.uploadImgShowBase64 = true
      this.editor.customConfig.showLinkImg = false
      this.editor.customConfig.uploadImgServer = 'https://api.zgwyzxw.cn/files/'
      this.editor.customConfig.uploadImgParams = {
        prefix: 'article'
      }
      this.editor.customConfig.uploadImgHeaders = {
        'Authorization': `Bearer ${loadToken()}\n`
      }
      this.editor.create()
    })
  },
  components: {
    CasCader, UploadImage
  },
  computed: {
    headers() {
      return {
        'Authorization': `Bearer ${loadToken()}\n`
      }
    },
    handleOptions() {
      return tagOption().slice(1)
    }
  }
}
</script>

<style lang="scss">
@import "~common/sass/variable.scss";
.post-article {
    margin: 10px 10px 80px 20px;
    padding: 30px 20px 20px 0;
    border: 1px solid $border-color;
}
.editor-wrapper {
    margin: 40px 0 25px 20px;
}
.el-cascader-menus{
  z-index: 1000000!important;
}
</style>
